﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TogheterWeBuyIt.Models;
using System.Web.Security;

namespace TogheterWeBuyIt.Controllers
{
    public class UsuarioController : Controller
    {
		private UsuarioRepository repo = new UsuarioRepository();
        //
        // GET: /Usuario/

		public ActionResult LogOff()
		{
			FormsAuthentication.SignOut();
			Session["LoggedUserId"] = null;
			return RedirectToAction("Index", "Home");
		}

		public ActionResult LogIn()
		{
			return View();
		}

		[HttpPost]
		public ActionResult LogIn(LoginUsuarioModel user, string returnUrl)
		{
			Usuario logged = repo.Login(user.Login, user.Senha);
			if (logged != null)
			{
				if (String.IsNullOrEmpty(logged.Login)) throw new ArgumentException("Value cannot be null or empty.", "userName");

				FormsAuthentication.SetAuthCookie(logged.Login, user.Lembrar);
				Session["LoggedUserId"] = logged.Id;

				if (!String.IsNullOrEmpty(returnUrl))
				{
					return Redirect(returnUrl);
				}
				else
				{
					return RedirectToAction("Index", "Home");
				}
			}
			else
			{
				ModelState.AddModelError("", "The user name or password provided is incorrect.");
			}

			// If we got this far, something failed, redisplay form
			return View(user);
		}

        public ActionResult Index()
        {
            return View(repo.FindAllUsuarios());
        }

        //
        // GET: /Usuario/Details/5

        public ActionResult Details(int id)
        {
			Usuario user = repo.GetUsuario(id);
            return View(user);
        }

        //
        // GET: /Usuario/Create

        public ActionResult Create()
        {
            return View();
        } 

        //
        // POST: /Usuario/Create

        [HttpPost]
        public ActionResult Create(FormCollection collection)
        {
            try
            {
                // TODO: Add insert logic here
				Usuario user = new Usuario()
				{
					Login = collection["Login"],
					Senha = collection["Senha"],
					Email = collection["Email"],
					CPF = collection["CPF"],
					CNPJ = collection["CNPJ"],
					Nome = collection["Nome"]
				};

				if (!string.IsNullOrEmpty(user.CNPJ))
					user.IdTipo = ETipoUsuario.PessoaJuridica;
				else
					user.IdTipo = ETipoUsuario.PessoaFisica;

				repo.Add(user);
				

                return RedirectToAction("Index", "Home");
            }
            catch
            {
                return View();
            }
        }
        
        //
        // GET: /Usuario/Edit/5
 
        public ActionResult Edit(int id)
        {
			if (Session["LoggedUserId"] != null)
			{
				if (id == (int)Session["LoggedUserId"])
				{
					Usuario user = repo.GetUsuario(id);
					return View(user);
				}
			}

			return RedirectToAction("Details", new { id = id });
        }

        //
        // POST: /Usuario/Edit/5

        [HttpPost]
        public ActionResult Edit(int id, FormCollection collection)
        {
            try
            {
				
                // TODO: Add update logic here
				Usuario user = repo.GetUsuario(id);
				
				user.Id = id;
				user.Login = collection["Login"];
				user.Senha = collection["Senha"];
				user.Email = collection["Email"];
				user.CPF = collection["CPF"];
				user.CNPJ = collection["CNPJ"];
				user.Nome = collection["Nome"];

				if (!string.IsNullOrEmpty(user.CNPJ))
					user.IdTipo = ETipoUsuario.PessoaJuridica;
				else
					user.IdTipo = ETipoUsuario.PessoaFisica;

				repo.Save();
 
                return RedirectToAction("Index", "Home");
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /Usuario/Delete/5
 
        public ActionResult Delete(int id)
        {
            return View();
        }

        //
        // POST: /Usuario/Delete/5

        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add delete logic here
 
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
    }
}
